package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shopping-mall/models"
	"time"

	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *shopping_rpc.ProductListRequest) (*shopping_rpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	var products []struct {
		models.Product
		ClassName string
		UserName  string
	}
	var data []*shopping_rpc.FromProductList
	var total int64
	key := fmt.Sprintf("Lisr:%s,%d,%s", in.Order, in.Page, in.Title)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get == "" {
		sql := models.DB.Model(&models.Product{}).Joins("join users on products.user_id = users.id join classes on products.class_id = classes.id").Where("products.title like ?", "%"+in.Title+"%")
		if in.Order != "" {
			sql = sql.Order(in.Order + " desc")
		}
		err := sql.Limit(5).Offset(int(in.Page-1) * 5).Select("products.*,classes.name as class_name,users.name as user_name").Scan(&products).Error
		if err != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		for _, product := range products {
			get := shopping_rpc.FromProductList{
				UserName:     product.UserName,
				Title:        product.Title,
				Price:        float32(product.Price),
				BrowseNumber: int64(product.BrowseNumber),
				Image:        product.Image,
				ClassName:    product.ClassName,
			}
			data = append(data, &get)
		}
		set, _ := json.Marshal(&data)
		models.RDB.Set(models.Ctx, key, set, 24*time.Hour)
	} else {
		json.Unmarshal([]byte(get), &data)
	}
	if models.DB.Where("title like ?", "%"+in.Title+"%").Model(&models.Product{}).Count(&total).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &shopping_rpc.ProductListResponse{
		Products: data,
		Total:    total,
	}, nil
}
